package com.xiaoyu.lanling.feature.moment.data

import `in`.srain.cube.request.JsonData
import `in`.srain.cube.request.RequestDefaultHandler
import com.xiaoyu.base.net.RequestCreator
import com.xiaoyu.lanling.common.config.HttpConfig
import com.xiaoyu.lanling.event.moment.detail.CommentMomentEvent
import com.xiaoyu.lanling.event.moment.detail.LikeMomentEvent
import com.xiaoyu.lanling.event.moment.detail.MomentDetailEvent
import com.xiaoyu.lanling.feature.moment.model.MomentItem

object MomentData {

    fun getMomentDetail(requestTag: Any, fid: String) {
        RequestCreator.create<MomentDetailEvent>(requestTag, MomentDetailEvent::class.java)
                .addQueryData("fid", fid)
                .setPostEventWhenFail(true)
                .setRequestUrl(HttpConfig.LANLING_MOMENT_DETAIL_MOMENT)
                .enqueue()
    }

    fun like(requestTag: Any, moment: MomentItem, liked: Boolean) {
        if (liked)
            MomentTracker.like(moment)
        RequestCreator.create<LikeMomentEvent>(LikeMomentEvent::class.java)
                .setRequestUrl(HttpConfig.LANLING_MOMENT_LIKE)
                .addPostData("fid", moment.feed.id)
                .addPostData("status", if (liked) "enable" else "disable")
                .setRequestHandler(object : RequestDefaultHandler<LikeMomentEvent, JsonData>() {
                    override fun processOriginData(originData: JsonData): LikeMomentEvent {
                        return LikeMomentEvent(requestTag, moment.feed.id, moment.user.uid, originData.optJson("data"))
                    }

                    override fun onRequestFinish(event: LikeMomentEvent) {
                        event.post()
                    }
                })
                .enqueue()
    }

    /**
     *  @param fid  feedId
     *  @param cid  commentId , null if not reply to certain comment
     */
    fun comment(requestTag: Any, fid: String, uid: String, cid: String, comment: String) {
        RequestCreator.create<CommentMomentEvent>(CommentMomentEvent::class.java)
                .setRequestUrl(HttpConfig.LANLING_MOMENT_ADD_COMMENT)
                .setPostEventWhenFail(true)
                .addPostData("fid", fid)
                .addPostData("puid", uid)
                .addPostData("pcid", cid)
                .addPostData("text", comment)
                .setRequestHandler(object : RequestDefaultHandler<CommentMomentEvent, JsonData>() {
                    override fun processOriginData(originData: JsonData): CommentMomentEvent {
                        return CommentMomentEvent(requestTag, originData, uid, fid)
                    }

                    override fun onRequestFinish(event: CommentMomentEvent) {
                        event.post()
                    }
                })
                .enqueue()
    }
}

